//
//  UIImage+UIImage_Compress.m
//  YuanXinKit
//
//  Created by 晏德智 on 2016/11/3.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "UIImage+Compress.h"
#import <MobileCoreServices/MobileCoreServices.h>

@implementation UIImage (Compress)

- (NSData *)dataFromImage:(UIImage *)image metadata:(NSDictionary *)metadata mimetype:(NSString *)mimetype
{
    NSMutableData *imageData = [NSMutableData data];
    CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef)mimetype, NULL);
    CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, uti, 1, NULL);

    if (imageDestination == NULL)
    {
        NSLog(@"Failed to create image destination");
        imageData = nil;
    }
    else
    {
        CGImageDestinationAddImage(imageDestination, image.CGImage, (__bridge CFDictionaryRef)metadata);

        if (CGImageDestinationFinalize(imageDestination) == NO)
        {
            NSLog(@"Failed to finalise");
            imageData = nil;
        }
        CFRelease(imageDestination);
    }

    CFRelease(uti);

    return imageData;
}

- (NSData *)dataByCompressToSize:(CGSize)size toQuality:(CGFloat)quality {
    UIImage *compressedImage = self;
    if (!CGSizeEqualToSize(size, CGSizeZero)) {
        UIGraphicsBeginImageContext(size);
        [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
        compressedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    NSData *data = [self dataFromImage:self metadata:nil mimetype:@"image/jpeg"];
    if ((quality >= 1) || (data.length < 5 * 1024 * 1024)) { // 小于 5M 不压缩
        return data;
    } else {
        return UIImageJPEGRepresentation([UIImage imageWithData:data], quality);
    }
}

- (UIImage *)imageByCompressToSize:(CGSize)size toQuality:(CGFloat)quality {
    UIImage *compressedImage = self;
    if (!CGSizeEqualToSize(size, CGSizeZero)) {
        UIGraphicsBeginImageContext(size);
        [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
        compressedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
     if (quality >= 1) {
        return compressedImage;
    } else {
        return [UIImage imageWithData:UIImageJPEGRepresentation(compressedImage, quality)];
    }
}

- (NSData *)dataByCompressToScale:(CGFloat)scale toQuality:(CGFloat)quality {
    return [self dataByCompressToSize:CGSizeMake(self.size.width * scale, self.size.height * scale) toQuality:quality];
}

- (UIImage *)imageByCompressToScale:(CGFloat)scale toQuality:(CGFloat)quality {
    return [self imageByCompressToSize:CGSizeMake(self.size.width * scale, self.size.height * scale) toQuality:quality];
}

@end
